<?php

namespace App\Jobs;

use App\Models\Activity;
use App\Models\Tools\Data;
use App\Models\Tools\Period;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LotteryDrawOvertime implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $participate_id;

    /**
     * Create a new job instance.
     *
     * @param int $participate_id
     * @return void
     */
    public function __construct($participate_id)
    {
        $this->participate_id = $participate_id;
    }

    /**
     * Execute the job.
     * 霸王餐预开奖超时验证
     *
     * @return void
     */
    public function handle()
    {
        try{
            DB::beginTransaction();
            // 查询达人参与信息
            $participate = DB::table('lottery_users_draw')->where('participate_id', '=', $this->participate_id)->lockForUpdate()->first();
            $participate = json_decode(json_encode($participate), true);

            // 如果开奖已经完成，直接结束
            if ($participate['status'] === Data::DATA_DB_LOTTERY_USERS_DRAW_STATUS_WIN) {
                DB::rollBack();
                return;
            }

            // 修改当前中奖人的状态
            DB::table('lottery_users_draw')
                ->where('participate_id', '=', $this->participate_id)
                ->update([
                    'status'=>Data::DATA_DB_LOTTERY_USERS_DRAW_STATUS_OVERTIME,
                ]);

            // 查询活动信息
            $activity = DB::table('lottery_activity')->where('act_id', '=', $participate['act_id'])->first();
            $activity = json_decode(json_encode($activity), true);

            // 随机查一个参与人，如果没有直接结束活动
            $participates = Activity::findParticipate($activity['act_id']);
            if(!$participates){
                Activity::drawCancel($activity,'所有参与人都未接受开奖，活动取消');
                DB::commit();
                return;
            }

            // 更新用户为预中奖状态
            DB::table('lottery_users_draw')
                ->where('participate_id','=',$participates['participate_id'])
                ->update([
                    'status'=>Data::DATA_DB_LOTTERY_USERS_DRAW_STATUS_WINING,
                    'win_at'=>date('Y-m-d H:i:s'),
                    'cancel_at'=>date('Y-m-d H:i:s',time() + Period::getSetting('LOTTERY_NEXT_MEMBER')),
                ]);


            // 超时换下一位
            $end_time = date('Y-m-d H:i:s', time() + Period::getSetting('LOTTERY_NEXT_MEMBER'));
            $delay = Activity::drawTime($end_time);
            LotteryDrawOvertime::dispatch($participates['participate_id'])->delay($delay);

            DB::commit();

            // 选择完成，发送预中奖通知
            Activity::sendConfirmMessage($activity, $participates);
        }catch (\Exception $e){
            DB::rollBack();
            Log::emergency(LotteryDraw::class, ['participate_id' => $this->participate_id, 'msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
        }
    }
}
